import qiniu
from flask import current_app


access_key = "rgHQQUCP0wuQq6efF36CGvhzP_wuP6SQxdrsQXmj"
secret_key = "Yb604_rU_1P617xoYJD6BvczJk2ACDASqnHbBEGy"
bucket_name = "wyzzxx"


def pic_storage(data):
    """将图片二进制数据上传到七牛云"""
    q = qiniu.Auth(access_key, secret_key)
    # key = 'hello'
    # data = 'hello qiniu!'
    token = q.upload_token(bucket_name)
    if not data:
        return AttributeError('图片数据为空')
    try:
        ret, info = qiniu.put_data(token, None, data)
    except Exception as e:
        current_app.logger.error(e)
        raise e
    # if ret is not None:
    #     print('All is OK')
    # else:
    #     print(info)  # error message in info
    # 工具类如果产生异常千万别私自处理，应该抛出，方便调用者查询异常所在。
    if info.status_code != 200:
        raise Exception('图片上传到七牛云失败')
    return ret['key']


if __name__ == '__main__':
    file = input("请输入图片地址：")
    with open(file, 'rb') as f:
        data = f.read()
        pic_storage(data)